#include <iostream>
#include <unistd.h>
#include <string>

#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


void usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " ip port\n" << std::endl;
}


int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }  

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    // 1.创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    // 不需要显示绑定bind，OS自动选择port
    // 2.向服务端发起建立连接的请求connect
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(3);
    }

    // 连接成功
    std::cout << "connect success" << std::endl;
    while (true)
    {
        std::string line;
        std::cout << "请输入: ";
        std::getline(std::cin, line);

        send(sock, line.c_str(), line.size(), 0);
        char buffer[1024];
        ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << "server echo: " << buffer << std::endl;
        }
        else if (s == 0)
        {
            // 对端关闭
            break;
        }
        else
        {
            break;
        }
    }
    close(sock);
    return 0;
}
